/*
	Copyright (C) 2010 Salil Bhagurkar

	This file is part of salil64

	salil64 is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	salil64 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with salil64.  If not, see <http://www.gnu.org/licenses/>.
*/

#define BITMAP64_DIV 64

int getBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i = nr / BITMAP64_DIV;
	int bit = nr % BITMAP64_DIV;
	return (bitmap[i] & (1UL << bit)) ? 1 : 0;
}

void setBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i = nr / BITMAP64_DIV;
	int bit = nr % BITMAP64_DIV;
	bitmap[i] |= (1UL << bit);
}

void clrBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i = nr / BITMAP64_DIV;
	int bit = nr % BITMAP64_DIV;
	bitmap[i] &= ~(1UL << bit);
}

unsigned long findSetBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i;
	for(i = 0; i < nr; i++) {
		if(getBit(bitmap, i)) {
			return i;
		}
	}
}

unsigned long findClrBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i;
	for(i = 0; i < nr; i++) {
		if(!getBit(bitmap, i)) {
			return i;
		}
	}
}

unsigned long countBit(unsigned long *bitmap, unsigned long nr)
{
	unsigned long i;
	unsigned long count = 0;
	for(i = 0; i < nr; i++) {
		if(getBit(bitmap, i))
			count++;
	}
	return count;
}
